package com.example.service;

import com.example.common.JwtTokenUtils;
import com.example.dao.AdminDao;
import com.example.entity.Admin;
import com.example.entity.Params;
import com.example.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService {
    @Resource
    private AdminDao adminDao;

    public List<Admin> findAll() {
        return adminDao.selectAll();
    }

    public PageInfo<Admin> findBySearch(Params params) {
        //分页查询
        PageHelper.startPage(params.getPageNum(),params.getPageSize());

        List<Admin> list = adminDao.findBySearch(params);
        return PageInfo.of(list);
    }

    public void add(Admin admin) {
        if (admin.getName() == null || admin.getName().isEmpty()) {
            throw new CustomException("名称不能为空");
        }
        if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
            throw new CustomException("密码不能为空");
        }
        if (admin.getRole() == null || admin.getRole().isEmpty()) {
            admin.setRole("学生");
        }
        Admin user = adminDao.findByName(admin.getName());
        if(user!=null){
            throw new CustomException("该用户名已存在，请勿重复添加");
        }
        adminDao.insertSelective(admin);
    }

    public void update(Admin admin) {
        adminDao.updateByPrimaryKeySelective(admin);
    }

    public void delete(Integer id) {
        adminDao.deleteByPrimaryKey(id);
    }

    public Admin login(Admin admin) {
        if (admin.getName() == null || admin.getName().isEmpty()) {
            throw new CustomException("名称不能为空");
        }
        if (admin.getName() == null || admin.getName().isEmpty()) {
            throw new CustomException("密码不能为空");
        }
        Admin user = adminDao.findByNameAndPassword(admin.getName(),admin.getPassword());
        if (user==null){
            throw new CustomException("用户名或密码错误");
        }
        //生成token
        String token = JwtTokenUtils.genToken(user.getId().toString(),user.getPassword());
        user.setToken(token);
        return user;
    }

    public Admin findByid(Integer id) {
        return adminDao.selectByPrimaryKey(id);
    }

    public void updatePassword(Admin admin) {
        Admin user = JwtTokenUtils.getCurrentUser();
        user.setPassword(admin.getPassword());
        adminDao.updateByPrimaryKeySelective(user);
    }
}
